<template>
  <div class="app-container">
    <!-- 桌面端左右布局 -->
    <el-row :gutter="10" v-if="!isMobile">
      <el-col :span="showTree ? 6 : 0">
        <CourseTree :title="title" @search="getList1" />
      </el-col>
      <el-col :span="showTree ? 18 : 24">
        <div class="course_content">
          <el-row type="flex" justify="around" style="width: 100%">
            <el-col :span="20">
              <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
                <el-form-item label="考试类别" prop="type">
                  <el-select v-model="queryParams.type" placeholder="请选择.." clearable size="small" @change="handleQuery">
                    <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>
                <el-form-item label="考试状态" prop="state">
                  <el-select v-model="queryParams.state" placeholder="请选择.." clearable size="small" @change="handleQuery">
                    <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>
                <el-form-item label="阅卷人" prop="manager">
                  <el-select v-model="queryParams.manager" placeholder="请选择.." filterable clearable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in managerOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" size="mini" @click="handleQuery" :style="{
                    backgroundColor: theme,
                    borderColor: theme
                  }">搜索</el-button>
                  <el-button size="mini" @click="resetQuery">清空</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" :showTree.sync="showTree" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-table :data="List" style="width: 100%; margin-top: 20px" :show-header="true"
            :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }"
            @row-dblclick="handleUpdate" v-loading="loading">
            <el-table-column width="220" label="考试信息">
              <template slot-scope="scope">
                <el-row style="width: 100%">
                  <el-col :span="24">
                    <el-row type="flex" justify="left">
                      <el-col :span="24" class="course_name">
                        {{ scope.row.name }}</el-col>
                    </el-row>
                    <el-row style="width: 100%">
                      <el-col :span="24" class="create_time">考试类型 ：{{
                        scope.row.type | ExamTypeFormat
                      }}</el-col>
                    </el-row>
                    <el-row style="width: 100%">
                      <el-col :span="24" class="create_time">
                        考试时限：{{ scope.row.time_limit }}分钟</el-col>
                      <el-col :span="24" class="create_time">
                        开始时间：{{
                          scope.row.start_time | formatDate
                        }}</el-col>
                      <el-col :span="24" class="create_time">
                        结束时间：{{ scope.row.end_time | formatDate }}</el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>

            <el-table-column label="考试分类">
              <template slot-scope="scope">
                <span>{{ scope.row.course.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="阅卷人">
              <template slot-scope="scope">
                <span v-if="scope.row.manager!==undefined&&scope.row.manager.name">{{ scope.row.manager.name }}</span>
                <span v-else>暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="考试总分">
              <template>
                <span :style="{ color: theme }">100</span>
              </template>
            </el-table-column>
            <el-table-column label="及格分">
              <template slot-scope="scope">
                <span :style="{ color: theme }">{{
                  scope.row.qualify_score
                }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="!showTree" label="参考人数">
              <template slot-scope="scope">
                <span>{{ scope.row.user.length }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="!showTree" label="参考人员">
              <template slot-scope="scope">
                <span v-for="user in scope.row.user" :key="user.id">{{ user.name }}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="考试状态">
              <template slot-scope="scope">
                <span>{{ scope.row.state | stateFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="130">
              <template slot-scope="scope">
                <el-row :gutter="10">
                  <el-col :span="1.5" >
                    <el-tooltip class="item" effect="dark" content="去考试" placement="top">
                      <el-button v-if="scope.row.state === 1" icon="el-icon-caret-right" type="primary" size="mini"
                        @click="handlePre(scope.row.id)" :style="{
                          backgroundColor: theme,
                          borderColor: theme,
                          fontWeight: 'bold'
                        }" v-hasPermi="['exam:paper:query']">去考试</el-button>
                    </el-tooltip>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size"
            @pagination="getList" />
        </div>
      </el-col>
    </el-row>

    <!-- 移动端上下布局 -->
    <template v-if="isMobile">
      <!-- 移动端骨架屏 -->
      <mobile-skeleton 
        v-if="loading" 
        :showHeader="false"
        :showSearch="true" 
        :searchFields="2"
        :cardsCount="3"
        :showPagination="total > 0"
      />
      
      <template v-else>
        <!-- 移动端分类树 -->
        <div v-if="showTree" class="mobile-tree-container">
          <div class="mobile-tree-header">
            <span :style="{ color: theme }">{{ title }}</span>
            <el-button 
              type="text" 
              icon="el-icon-arrow-up" 
              @click="showTree = false" 
              :style="{ color: theme }"
              v-if="showTree">
              收起
            </el-button>
          </div>
          <CourseTree :title="title" @search="getList1" />
        </div>
        <div v-else class="mobile-tree-toggle">
          <el-row :gutter="10">
            <el-col :span="24">
              <el-button 
                type="primary" 
                size="small" 
                icon="el-icon-arrow-down"
                @click="showTree = true"
                :style="{
                  backgroundColor: theme,
                  borderColor: theme,
                  width: '100%',
                  marginBottom: '10px',
                  borderRadius: '4px',
                  height: '36px'
                }">
                展开考试分类
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 移动端搜索表单 -->
        <div class="course_content">
          <el-row type="flex" justify="around" style="width: 100%" class="mobile-search">
            <el-col :span="24">
              <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" class="mobile-form">
                <el-form-item label="考试类别" prop="type">
                  <el-select v-model="queryParams.type" placeholder="请选择.." clearable size="small" @change="handleQuery">
                    <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>
                <el-form-item label="考试状态" prop="state">
                  <el-select v-model="queryParams.state" placeholder="请选择.." clearable size="small" @change="handleQuery">
                    <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" size="mini" @click="handleQuery" :style="{
                    backgroundColor: theme,
                    borderColor: theme,
                  }">搜索</el-button>
                  <el-button size="mini" @click="resetQuery">清空</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>

          <!-- 移动端卡片视图 -->
          <div class="mobile-card-view">
            <div v-if="List.length === 0" class="empty-data">
              <i class="el-icon-document"></i>
              <p>暂无数据</p>
            </div>
            
            <el-card v-for="(item, index) in List" :key="index" class="mobile-card" shadow="hover">
              <div slot="header" class="card-header">
                <div class="exam-title" :style="{ color: theme }">{{ item.name }}</div>
                <div class="card-actions">
                  <el-tooltip effect="dark" content="去考试" placement="top" v-if="item.state === 1">
                    <span @click="handlePre(item.id)" 
                      :style="{ color: theme, fontSize: '18px' }" 
                      v-hasPermi="['exam:paper:query']">
                      <i class="el-icon-caret-right"></i>
                    </span>
                  </el-tooltip>
                </div>
              </div>
              <div class="card-content">
                <div class="exam-info">
                  <div class="info-item">
                    <span class="label">考试类型：</span>
                    <span class="value">{{ item.type | ExamTypeFormat }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">考试分类：</span>
                    <span class="value">{{ item.course.name }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">阅卷人：</span>
                    <span class="value" v-if="item.manager && item.manager.name">{{ item.manager.name }}</span>
                    <span class="value" v-else>暂无</span>
                  </div>
                  <div class="info-item">
                    <span class="label">考试状态：</span>
                    <el-tag size="small" :type="getStateTagType(item.state)">{{ item.state | stateFilter }}</el-tag>
                  </div>
                </div>
                <div class="exam-details" v-if="expandedCards[index]">
                  <div class="details-section">
                    <div class="info-item">
                      <span class="label">考试时限：</span>
                      <span class="value">{{ item.time_limit }}分钟</span>
                    </div>
                    <div class="info-item">
                      <span class="label">开始时间：</span>
                      <span class="value">{{ item.start_time | formatDate }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">结束时间：</span>
                      <span class="value">{{ item.end_time | formatDate }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">考试总分：</span>
                      <span class="value" :style="{ color: theme, fontWeight: 'bold' }">100</span>
                    </div>
                    <div class="info-item">
                      <span class="label">及格分：</span>
                      <span class="value" :style="{ color: theme, fontWeight: 'bold' }">{{ item.qualify_score }}</span>
                    </div>
                  </div>
                </div>
                <div class="card-toggle">
                  <el-button type="text" size="small" @click.stop="expandCard(index)">
                    {{ expandedCards[index] ? '收起' : '查看详情' }}
                    <i :class="expandedCards[index] ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                  </el-button>
                </div>
                <div class="card-actions-footer" v-if="item.state === 1">
                  <el-button 
                    type="primary"
                    @click="handlePre(item.id)"
                    :style="{
                      backgroundColor: theme,
                      borderColor: theme,
                      width: '100%',
                      marginTop: '10px'
                    }"
                    v-hasPermi="['exam:paper:query']">
                    去考试
                  </el-button>
                </div>
              </div>
            </el-card>
            
            <!-- 移动端分页 -->
            <div class="mobile-pagination" v-if="total > 0">
              <div class="mobile-pagination-wrapper">
                <!-- 第一行：总数和每页条数 -->
                <div class="pagination-row top-row">
                  <span class="el-pagination__total">共 {{ total }} 条</span>
                  <el-select 
                    v-model="queryParams.page_size" 
                    size="mini" 
                    class="el-pagination__sizes"
                    @change="handleSizeChange">
                    <el-option
                      v-for="item in [10, 20, 30, 50]"
                      :key="item"
                      :label="`${item}条/页`"
                      :value="item">
                    </el-option>
                  </el-select>
                </div>
                
                <!-- 第二行：页码导航 -->
                <div class="pagination-row bottom-row">
                  <el-pagination
                    background
                    @current-change="handleCurrentChange"
                    :current-page="queryParams.page"
                    :page-size="queryParams.page_size"
                    layout="prev, pager, next, jumper"
                    :total="total">
                  </el-pagination>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </template>
  </div>  
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import { getExamOwn, ExamCheck, delExam } from "@/api/vadmin/exam/exam";
import { listUser } from "@/api/vadmin/permission/user";
import CourseTree from "@/components/CourseTree";
import MobileSkeleton from "@/components/MobileSkeleton";
import "@/assets/styles/mobile/exam.scss";
export default {
  name: "test",
  components: { CourseTree, MobileSkeleton },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 题库分类
      title: "考试类别",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示树
      showTree: true,
      // 总条数
      total: 0,
      // 课程表格数据
      List: [],
      stateOptions: [
        { dictLabel: "待开放", dictValue: 0 },
        { dictLabel: "已开放", dictValue: 1 },
        { dictLabel: "已结束", dictValue: 2 },
      ],
      typeOptions: [
        { dictLabel: "正常考试", dictValue: 1 },
        { dictLabel: "认证考试", dictValue: 2 },
        { dictLabel: "培训考试", dictValue: 3 },
        { dictLabel: "以考代训", dictValue: 4 },
      ],
      managerOptions: [],
      userOptions: [],
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        create_datetime: undefined,
        name: undefined,
      },
      intervalId: null,
      isMobile: false,
      mediaQueryList: null,
      expandedCards: {},
    };
  },
  computed: {
    ...mapState(["settings",'is_superuser','admin',"id"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
    is_superuser() {
      return this.$store.state.user.is_superuser;
    },
    admin() {
      return this.$store.state.user.admin;
    },
    id() {
      return this.$store.state.user.id;
    }
  },
  filters: {
    stateFilter(val) {
      const state = {
        0: "未开始",
        1: "进行中",
        2: "已结束",
      };
      return state[val];
    },
  },

  created() {
    this.getList();
    this.getUsers();
    this.startRefreshTimer();
  },
  
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 清除定时器
    this.clearRefreshTimer();
    
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },

  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    reset() {
      this.queryParams = {
        page: 1,
        page_size: 10,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 考试状态刷新 */
    getExamCheck() {
      ExamCheck().then((res) => {
        this.getList();
      });
    },
    getBasicData() {
      // 获取阅卷人
      listUser({ page_size: 10000, page: 1 }).then((response) => {
        this.managerOptions = response.results;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getExamOwn(this.queryParams).then((response) => {
        this.List = response.results;
        this.total = response.count;
        this.loading = false;
      });
    },
    /** 查询列表 */
    getList1(data) {
      if (data.id) {
        this.loading = true;
        this.queryParams.course = data.id;
        getExamOwn(this.queryParams).then((response) => {
          this.List = response.results;
          this.total = response.count;
          this.loading = false;
        });
      } else {
        
        this.queryParams.course = "";
        getExamOwn(this.queryParams).then((response) => {
          this.List = response.results;
          this.total = response.count;
          this.loading = false;
        });
      }
    },

    /*去考试 */
    handlePre(id) {
      this.$router.push({
        name: "Preview",
        params: { id: id },
      });
    },
    /*新增考试 */
    handleAdd() {
      this.$router.push({ name: "Newexam" });
    },
    /*修改试卷 */
    handleUpdate(row) {
      this.$router.push({ name: "Newexam", params: { id: row.id } });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$confirm("是否确认删除考试：" + row.name + "?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delExam(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    getUsers() {
      listUser({ page_size: 10000, page: 1 }).then((response) => {
        // console.log("参考人员", response.results);
        this.userOptions = response.results;
      });
    },
    expandCard(index) {
      this.$set(this.expandedCards, index, !this.expandedCards[index]);
    },
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    },
    getStateTagType(state) {
      const stateType = {
        0: 'info',
        1: 'warning',
        2: 'success',
      };
      return stateType[state] || 'info';
    },
    /** 开始刷新定时器 */
    startRefreshTimer() {
      // 如果已经有定时器在运行，先清除它
      this.clearRefreshTimer();
      
      // 创建新的定时器
      this.intervalId = setInterval(() => {
        this.getExamCheck();
      }, 20000); // 每20秒刷新一次
    },
    
    /** 清除刷新定时器 */
    clearRefreshTimer() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
  padding: 0;
}
</style>